// pages/post_detail/post_detail.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user_id: '',
    post_id: '',
    comment: [],
    post: {},
    post_img: [],
    ishidden: true,
    value: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.setData({
      post_id: options.post_id
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var value = wx.getStorageSync('user_id');
    if (value && this.data.post_id) {
      this.getPostDetail();
      this.setData({
        user_id: value
      })
    } else {
      app.login()
      .then(app.doLogin)
      .then(app.checkAuth('scope.userInfo'))
      .then(app.getUserInfo)
      .then(app.setUserData)
      .then(this.getPostDetail)
      .catch(app.toLoad)
    }
  },

  getPostDetail: function () {
    let that = this;
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://rtutrip.aihuodong.top/index/index/get_post_data',
        data: {
          post_id: that.data.post_id
        },
        success(res) {
          console.log(res.data)
          if (res.data.data.post.post_img) {
            var post_img = res.data.data.post.post_img.split(',');
            that.setData({
              post_img: post_img
            })
          }
          that.setData({
            post: res.data.data.post,
            comment: res.data.data.comment
          })
          resolve(res);
        }
      })
    })
  },
  showDialog: function () {
    this.setData({
      ishidden: !this.data.ishidden
    })
  },
  bindFormSubmit: function (e) {
    var that = this;
    console.log(e.detail.value.textarea)
    if (e.detail.value.textarea == "") {
      wx.showToast({
        title: '评论内容不能为空！',
        icon: 'none',
        duration: 2000
      })
    } else {
      wx.request({
        url: 'https://rtutrip.aihuodong.top/index/index/set_comment_data',
        data: {
          post_id: that.data.post_id,
          user_id: that.data.user_id,
          comment_text: e.detail.value.textarea
        },
        success(res) {
          that.getPostDetail();
          that.setData({
            ishidden: !that.data.ishidden,
            value: ''
          })
        }
      })
    }
  },
  onShareAppMessage: function (res) {
    const _this = this
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: _this.data.post.post_title,
      path: '/pages/post_detail/post_detail?post_id=' + _this.data.post_id
    }
  }
})